module.exports = class pageRootsObj {
	constructor(arg) {
		this.pageRoots = {};
		this.currentVm = null;
	}

	setCurrentVm(vm) {
		this.currentVm = vm;
	}
	
	getCurrentVm() {
		return this.currentVm;
	}

	setPageContext(vm, ContextType) {
		// console.log(vm, ContextType)
		const id = this.getParentId(vm);
		// console.log(id)
		if (!this.pageRoots[id]) this.pageRoots[id] = {};
		this.pageRoots[id][ContextType] = vm;
	}

	clearPageContext(vm, ContextType) {
		const id = this.getParentId(vm);
		if (this.pageRoots[id]) {
			if (this.pageRoots[id][ContextType]) this.pageRoots[id][ContextType] = null;
			if (!Object.keys(this.pageRoots[id]).length) this.pageRoots[id] = null;
		}
	}

	getCurrentPageContext(ContextType) {
		return this.getPage(this.getCurrentVm(), ContextType);
	}

	getPage(page, ContextType) {
		// console.log('getPage', page)
		if(!page) return;
		const id = this.getId(page);
		// console.log(id)
		const r = this.pageRoots[id] && this.pageRoots[id][ContextType];
		return r;
	}

	getParentId(vm) {
		let p = vm.$parent;
		// #ifdef H5
		if(p && !vm.route) {
			return this.getParentId(p);
		}
		// #endif
		// #ifndef H5
		if(p) {
			return this.getParentId(p);
		}
		// #endif
		
		// #ifdef APP-NVUE
		return vm.route;
		// #endif
		// #ifndef APP-NVUE
		return vm._uid || vm.$vm._uid;
		// #endif
	}

	getId(page) {
		// console.log('getId', page)
		// #ifdef APP-NVUE
		return page.route;
		// #endif
		// #ifndef APP-NVUE
		return  page._uid || page.$vm._uid;
		// #endif
	}
}